<template>
  <div class="screen-sharing-page" :class="{ 'fullscreen-mode': isFullscreen }">
    <!-- 全屏模式 -->
    <div v-if="isFullscreen" class="fullscreen-container" ref="fullscreenContainer">
      <!-- 屏幕显示区域 -->
      <div class="screen-display" ref="screenDisplay">
        <img
          v-if="fullscreenScreenData"
          :src="fullscreenScreenData"
          alt="屏幕共享"
          class="screen-image"
        />

        <div v-else class="screen-placeholder">
          <el-icon class="placeholder-icon"><Monitor /></el-icon>
          <div class="placeholder-text">
            {{ fullscreenConnectionStatus === 'connected' ? '等待屏幕数据...' : '连接中...' }}
          </div>
          <el-progress
            v-if="fullscreenConnectionStatus === 'connecting'"
            :percentage="connectionProgress"
            :show-text="false"
            style="width: 200px; margin-top: 20px;"
          />
        </div>
      </div>

      <!-- 控制面板 -->
      <div class="control-panel" :class="{ 'hidden': controlsHidden }">
        <div class="panel-content">
          <div class="panel-info">
            <span class="client-info">{{ fullscreenClientInfo.name || `客户端 ${fullscreenClientId}` }}</span>
            <span class="connection-status" :class="fullscreenConnectionStatus">
              {{ fullscreenConnectionStatusText }}
            </span>
          </div>

          <div class="panel-actions">
            <el-button
              size="small"
              @click="saveClientRecording(fullscreenClientId)"
              type="warning"
            >
              <el-icon><VideoCamera /></el-icon>
              保存录屏
            </el-button>

            <el-button
              size="small"
              @click="exitFullscreen"
              type="danger"
            >
              <el-icon><Close /></el-icon>
              退出全屏
            </el-button>

            <el-button
              size="small"
              @click="toggleStats"
              :type="showStats ? 'primary' : 'default'"
            >
              <el-icon><DataAnalysis /></el-icon>
              统计
            </el-button>

            <el-button size="small" @click="refreshFullscreenScreen">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 统计面板 -->
      <div v-if="showStats" class="stats-panel">
        <div class="stats-header">
          <span class="stats-title">实时统计</span>
          <el-button size="small" text @click="showStats = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="stats-content">
          <div class="stat-row">
            <span class="stat-label">客户端:</span>
            <span class="stat-value">{{ fullscreenClientId }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">分辨率:</span>
            <span class="stat-value">{{ fullscreenScreenSharing?.resolution || '未知' }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">帧率:</span>
            <span class="stat-value fps">{{ fullscreenClientStats.fps || 0 }} FPS</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">延迟:</span>
            <span class="stat-value" :class="fullscreenLatencyClass">{{ fullscreenClientStats.latency || 0 }} ms</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">数据量:</span>
            <span class="stat-value">{{ fullscreenClientStats.dataRate || 0 }} KB/s</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">连接时间:</span>
            <span class="stat-value">{{ formatUptime(connectionUptime) }}</span>
          </div>

          <div class="stat-row">
            <span class="stat-label">画质:</span>
            <span class="stat-value">{{ fullscreenScreenSharing?.quality || '未知' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 正常模式 -->
    <div v-else class="normal-mode">
      <!-- 顶部操作栏 -->
      <el-card class="top-actions-card">
        <div class="top-actions">
          <div class="action-group">
            <span class="action-label">快速导航：</span>
            <el-button type="primary" size="small" @click="goToRecordingManagement">
              <el-icon><VideoCamera /></el-icon>
              录屏记录管理
            </el-button>
            <el-button type="success" size="small" @click="goToScreenshotManagement">
              <el-icon><Picture /></el-icon>
              截屏记录管理
            </el-button>
          </div>

          <div class="action-group">
            <el-button type="info" size="small" @click="refreshScreens">
              <el-icon><Refresh /></el-icon>
              刷新所有屏幕
            </el-button>
            <el-button type="warning" size="small" @click="stopAllScreenSharing">
              <el-icon><VideoPause /></el-icon>
              停止所有共享
            </el-button>
          </div>
        </div>
      </el-card>

      <el-card>
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><VideoCamera /></el-icon>
              屏幕共享 ({{ onlineClients.length }} 个在线客户端)
            </span>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="refreshScreens">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <!-- 屏幕共享列表 -->
        <div class="screen-grid">
          <el-row :gutter="20">
            <el-col
              v-for="client in onlineClients"
              :key="client.id"
              :xs="24" :sm="12" :lg="8" :xl="6"
            >
              <ScreenClientCard
                :client="client"
                :screen-sharing="getScreenSharing(client.id)"
                :stats="getClientStats(client.id)"
                @start-sharing="startClientScreenSharing"
                @stop-sharing="stopClientScreenSharing"
                @view-fullscreen="viewClientFullScreen"
                @refresh="refreshClientScreenSharing"
                @save-recording="saveClientRecording"
                @take-screenshot="takeClientScreenshot"
              />
            </el-col>
          </el-row>

          <el-empty
            v-if="onlineClients.length === 0"
            description="暂无在线客户端"
            :image-size="100"
          />
        </div>
      </el-card>
    </div>

    <!-- 录屏保存对话框 -->
    <el-dialog
      v-model="recordingDialogVisible"
      title="保存录屏"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="recordingForm" label-width="120px">
        <el-form-item label="录制时间范围">
          <div class="time-range-container">
            <el-date-picker
              v-model="recordingForm.startTime"
              type="datetime"
              placeholder="开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px; margin-right: 10px;"
              @change="updateDuration"
            />
            <span style="margin: 0 10px;">至</span>
            <el-date-picker
              v-model="recordingForm.endTime"
              type="datetime"
              placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 200px;"
              @change="updateDuration"
            />
          </div>
        </el-form-item>

        <el-form-item label="录制时长">
          <el-input-number
            v-model="recordingForm.duration"
            :min="1"
            :max="60"
            :step="1"
            @change="updateEndTime"
            style="width: 150px;"
          />
          <span style="margin-left: 10px;">分钟</span>
        </el-form-item>

        <el-form-item label="预估文件大小">
          <el-tag type="info">{{ estimatedFileSize }}</el-tag>
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            基于当前帧率和画质估算，实际大小可能有差异
          </div>
        </el-form-item>


      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recordingDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSaveRecording"
            :loading="recordingSaving"
          >
            {{ recordingSaving ? '正在生成录屏...' : '开始生成录屏' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, reactive, ref, nextTick } from 'vue'
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useClientsStore } from '@/stores/clients'
import { useWebSocketStore } from '@/stores/websocket'
import ScreenClientCard from '@/components/ScreenClientCard.vue'
import {
  VideoCamera, Refresh, Picture, VideoPause, Monitor, DataAnalysis, Close
} from '@element-plus/icons-vue'
import { filesAPI } from '@/services/api'

const router = useRouter()
const route = useRoute()
const clientsStore = useClientsStore()
const wsStore = useWebSocketStore()

// 直连WebSocket连接管理
const directConnections = reactive(new Map())

// 全屏模式相关状态
const isFullscreen = ref(false)
const fullscreenClientId = ref(null)
const fullscreenContainer = ref()
const screenDisplay = ref()
const fullscreenScreenData = ref(null)
const controlsHidden = ref(false)
const showStats = ref(false)
const connectionProgress = ref(0)
const connectionUptime = ref(0)
const fullscreenConnectionStatus = ref('disconnected')

// 计算属性
const onlineClients = computed(() => clientsStore.onlineClients)

// 全屏模式计算属性
const fullscreenConnectionStatusText = computed(() => {
  const statusMap = {
    connected: '已连接',
    connecting: '连接中',
    disconnected: '已断开'
  }
  return statusMap[fullscreenConnectionStatus.value] || '未知'
})

const fullscreenClientInfo = computed(() => {
  return clientsStore.getClientById(fullscreenClientId.value) || {}
})

const fullscreenScreenSharing = computed(() => {
  return clientsStore.getScreenSharing(fullscreenClientId.value) || {}
})

const fullscreenClientStats = computed(() => {
  return wsStore.stats.get(fullscreenClientId.value) || {}
})

const fullscreenLatencyClass = computed(() => {
  const latency = fullscreenClientStats.value.latency || 0
  if (latency < 50) return 'latency-low'
  if (latency < 150) return 'latency-medium'
  return 'latency-high'
})

// 获取屏幕共享状态
const getScreenSharing = (clientId) => {
  return clientsStore.getScreenSharing(clientId)
}

// 获取客户端统计信息
const getClientStats = (clientId) => {
  return wsStore.stats.get(clientId)
}

// 屏幕共享控制方法
const startClientScreenSharing = async (clientId) => {
  try {
    // 1. 从客户端信息获取WebSocket URL
    const client = clientsStore.getClientById(clientId)
    if (!client) {
      ElMessage.error('客户端信息不存在')
      return
    }

    // 检查是否有WebSocket连接信息
    if (!client.websocket_url && (!client.ip || !client.websocket_port)) {
      ElMessage.error('客户端WebSocket服务不可用：缺少连接信息')
      console.error('Client info:', client)
      return
    }

    // 2. 先调用客户端API启动屏幕共享
    // 构建客户端API URL
    let clientApiUrl
    if (client.ip && client.websocket_port) {
      // 使用客户端的IP和端口（WebSocket端口通常也是HTTP API端口）
      clientApiUrl = `http://${client.ip}:${client.websocket_port}/api/v1/client/screen/start`
    } else {
      // 使用默认地址（本地测试）
      clientApiUrl = `http://127.0.0.1:8090/api/v1/client/screen/start`
    }


    const startResponse = await fetch(clientApiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        quality: 80,
        fps: 15
      }),
      mode: 'cors' // 明确指定CORS模式
    })

    if (!startResponse.ok) {
      const errorText = await startResponse.text()
      throw new Error(`启动屏幕共享失败: ${startResponse.status} ${errorText}`)
    }

    // 3. 直接连接客户端WebSocket
    // 修复WebSocket URL构建逻辑，直接使用数字ID
    const wsClientId = clientId.toString() // 直接使用数字ID，不添加前缀
    let wsUrl
    if (client.websocket_url) {
      // 如果客户端有websocket_url，直接使用
      wsUrl = `${client.websocket_url}?client_id=${wsClientId}`
    } else if (client.ip && client.websocket_port) {
      // 根据客户端IP和端口构建WebSocket URL
      wsUrl = `ws://${client.ip}:${client.websocket_port}/ws?client_id=${wsClientId}`
    } else {
      // 使用默认地址（本地测试）
      wsUrl = `ws://127.0.0.1:8090/ws?client_id=${wsClientId}`
    }


    const ws = new WebSocket(wsUrl)

    ws.onopen = () => {
      clientsStore.startScreenSharing(clientId)
      ElMessage.success('已启动屏幕共享')
    }

    ws.onmessage = (event) => {
      try {
        // 先尝试解析JSON
        const data = JSON.parse(event.data)

        if (data.type === 'screen_frame') {
          // 更新屏幕显示
          updateScreenDisplay(clientId, data)
        }
      } catch (error) {
        // 如果不是JSON，可能是二进制数据
        console.error('Failed to parse WebSocket message:', error)
      }
    }

    ws.onclose = (event) => {
      directConnections.delete(clientId)
      clientsStore.stopScreenSharing(clientId)

      // 如果不是正常关闭，显示错误信息
      if (event.code !== 1000) {
        ElMessage.warning(`屏幕共享连接断开 (${event.code})`)
      }
    }

    ws.onerror = (error) => {
      console.error(`WebSocket error for client ${clientId}:`, error)
      ElMessage.error('WebSocket连接错误')
    }

    // 添加心跳保持连接
    const heartbeatInterval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }))
      } else {
        clearInterval(heartbeatInterval)
      }
    }, 30000) // 每30秒发送一次心跳

    // 保存连接引用和心跳定时器
    directConnections.set(clientId, { ws, heartbeatInterval })

  } catch (error) {
    console.error('Failed to start screen sharing:', error)
    ElMessage.error('启动屏幕共享失败: ' + error.message)
  }
}

const stopClientScreenSharing = async (clientId) => {
  try {
    // 1. 关闭WebSocket连接和心跳
    const connection = directConnections.get(clientId)
    if (connection) {
      if (connection.ws) {
        connection.ws.close()
      }
      if (connection.heartbeatInterval) {
        clearInterval(connection.heartbeatInterval)
      }
      directConnections.delete(clientId)
    }

    // 2. 调用客户端API停止屏幕共享
    const client = clientsStore.getClientById(clientId)
    if (client) {
      // 构建客户端API URL
      let clientApiUrl
      if (client.ip && client.websocket_port) {
        clientApiUrl = `http://${client.ip}:${client.websocket_port}/api/v1/client/screen/stop`
      } else {
        clientApiUrl = `http://127.0.0.1:8090/api/v1/client/screen/stop`
      }

      await fetch(clientApiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      })
    }

    clientsStore.stopScreenSharing(clientId)



    ElMessage.success('已停止屏幕共享')
  } catch (error) {
    console.error('Failed to stop screen sharing:', error)
    ElMessage.error('停止屏幕共享失败: ' + error.message)
  }
}

// 更新屏幕显示
const updateScreenDisplay = (clientId, frameData) => {
  // 根据客户端WebSocket实现，字段名称是 frame_data
  const imageData = frameData.frame_data || frameData.FrameData || frameData.frameData || frameData.data

  if (imageData) {
    const base64Image = `data:image/jpeg;base64,${imageData}`

    // 更新屏幕共享数据
    clientsStore.updateScreenSharing(clientId, {
      active: true,
      imageData: base64Image,
      resolution: `${frameData.width || frameData.Width || '1920'}x${frameData.height || frameData.Height || '1080'}`,
      quality: frameData.quality || frameData.Quality || 'high',
      timestamp: frameData.timestamp || frameData.Timestamp || Date.now()
    })





    // 更新性能统计信息
    updateClientStats(clientId, imageData.length, frameData.timestamp || frameData.Timestamp || Date.now())
  } else {
    console.warn('No image data found in frame for client:', clientId)
    console.warn('Available frame data keys:', Object.keys(frameData))
    console.warn('Frame data sample:', JSON.stringify(frameData).substring(0, 200) + '...')
  }
}



// 更新客户端性能统计
const updateClientStats = (clientId, frameSize, serverTimestamp) => {
  const now = Date.now()

  // 初始化统计信息（如果不存在）
  if (!wsStore.stats.has(clientId)) {
    wsStore.stats.set(clientId, {
      fps: 0,
      latency: 0,
      dataRate: 0,
      frameCount: 0,
      totalBytes: 0,
      lastFrameTime: now,
      startTime: now,
      frameTimestamps: [],
      lastUpdateTime: now
    })
  }

  const stats = wsStore.stats.get(clientId)

  // 计算延迟
  if (serverTimestamp) {
    const serverTime = new Date(serverTimestamp).getTime()
    stats.latency = Math.max(0, now - serverTime)
  } else {
    stats.latency = Math.max(0, now - stats.lastFrameTime)
  }

  // 计算帧率
  stats.frameTimestamps.push(now)
  stats.frameTimestamps = stats.frameTimestamps.filter(timestamp =>
    now - timestamp <= 1000
  )
  stats.fps = stats.frameTimestamps.length

  // 计算数据传输率
  stats.totalBytes += frameSize
  stats.frameCount++
  const elapsed = (now - stats.startTime) / 1000
  if (elapsed > 0) {
    stats.dataRate = Math.round(stats.totalBytes / elapsed / 1024) // KB/s
  }

  stats.lastFrameTime = now
  stats.lastUpdateTime = now

  // 更新统计信息
  wsStore.stats.set(clientId, stats)
}

const viewClientFullScreen = async (clientId) => {

  // 检查是否已经在共享
  if (!clientsStore.isScreenSharingActive(clientId)) {
    const errorMsg = '请先启动该客户端的屏幕共享'
    console.error(errorMsg)
    ElMessage.error(errorMsg)
    throw new Error(errorMsg)
  }

  // 进入全屏模式
  fullscreenClientId.value = clientId
  isFullscreen.value = true
  fullscreenConnectionStatus.value = 'connecting'


  // 等待DOM更新后请求全屏
  await nextTick()

  try {
    if (fullscreenContainer.value) {
      await fullscreenContainer.value.requestFullscreen()
    } else {
      throw new Error('Fullscreen container not found')
    }
  } catch (error) {
    console.error('Failed to enter fullscreen:', error)
    // 如果全屏失败，仍然保持全屏模式的UI状态
  }

  // 开始监听屏幕数据
  startFullscreenDataMonitoring()
}

const refreshClientScreenSharing = (clientId) => {
  wsStore.sendControlCommand(clientId, {
    action: 'refresh_screen'
  })
  ElMessage.success('已刷新屏幕')
}

// 全屏模式相关方法
const startFullscreenDataMonitoring = () => {
  // 直接监听屏幕共享数据更新
  const checkScreenData = () => {
    if (!fullscreenClientId.value) return

    const sharing = clientsStore.getScreenSharing(fullscreenClientId.value)
    if (sharing && sharing.imageData) {
      fullscreenScreenData.value = sharing.imageData
      fullscreenConnectionStatus.value = 'connected'
    }
  }

  // 定期检查屏幕数据
  const dataCheckInterval = setInterval(checkScreenData, 100)

  // 清理函数
  const cleanup = () => {
    clearInterval(dataCheckInterval)
  }

  // 立即检查一次
  checkScreenData()

  return cleanup
}

const exitFullscreen = async () => {
  try {
    if (document.fullscreenElement) {
      await document.exitFullscreen()
    }
  } catch (error) {
    console.error('Failed to exit fullscreen:', error)
  }

  // 重置全屏状态
  isFullscreen.value = false
  fullscreenClientId.value = null
  fullscreenScreenData.value = null
  fullscreenConnectionStatus.value = 'disconnected'
  controlsHidden.value = false
  showStats.value = false
}

const toggleStats = () => {
  showStats.value = !showStats.value
}

const refreshFullscreenScreen = () => {
  if (fullscreenClientId.value) {
    refreshClientScreenSharing(fullscreenClientId.value)
  }
}

const formatUptime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 录屏相关状态
const recordingDialogVisible = ref(false)
const currentRecordingClientId = ref(null)
const recordingSaving = ref(false)
const recordingForm = reactive({
  startTime: null,
  endTime: null,
  duration: 5 // 默认5分钟
})



const estimatedFileSize = computed(() => {
  if (!currentRecordingClientId.value || recordingForm.duration <= 0) return '0 MB'

  // 基于帧数和时长估算文件大小
  // 假设每帧平均50KB，15FPS
  const framesPerSecond = 15
  const avgFrameSize = 50 * 1024 // 50KB
  const totalFrames = recordingForm.duration * 60 * framesPerSecond
  const estimatedBytes = totalFrames * avgFrameSize

  if (estimatedBytes < 1024 * 1024) {
    return `${Math.round(estimatedBytes / 1024)} KB`
  } else if (estimatedBytes < 1024 * 1024 * 1024) {
    return `${Math.round(estimatedBytes / (1024 * 1024))} MB`
  } else {
    return `${Math.round(estimatedBytes / (1024 * 1024 * 1024) * 100) / 100} GB`
  }
})

const saveClientRecording = (clientId) => {
  currentRecordingClientId.value = clientId

  // 设置默认时间范围（最近5分钟）
  const now = new Date()
  recordingForm.endTime = now
  recordingForm.startTime = new Date(now.getTime() - 5 * 60 * 1000) // 5分钟前
  recordingForm.duration = 5

  recordingDialogVisible.value = true
}

// 录屏时间相关方法
const updateDuration = () => {
  if (recordingForm.startTime && recordingForm.endTime) {
    const start = new Date(recordingForm.startTime)
    const end = new Date(recordingForm.endTime)
    const diffMinutes = Math.round((end - start) / (1000 * 60))
    if (diffMinutes > 0 && diffMinutes <= 60) {
      recordingForm.duration = diffMinutes
    }
  }
}

const updateEndTime = () => {
  if (recordingForm.startTime && recordingForm.duration > 0) {
    const start = new Date(recordingForm.startTime)
    const end = new Date(start.getTime() + recordingForm.duration * 60 * 1000)
    recordingForm.endTime = end.toISOString().slice(0, 19).replace('T', ' ')
  }
}

// 确认保存录屏
const confirmSaveRecording = async () => {
  if (!currentRecordingClientId.value) {
    ElMessage.error('未选择客户端')
    return
  }

  if (!recordingForm.startTime || !recordingForm.endTime) {
    ElMessage.error('请选择录制时间范围')
    return
  }

  if (recordingForm.duration <= 0 || recordingForm.duration > 60) {
    ElMessage.error('录制时长必须在1-60分钟之间')
    return
  }

  // 验证时间范围
  const startTime = new Date(recordingForm.startTime)
  const endTime = new Date(recordingForm.endTime)

  // 检查时间逻辑是否合理
  if (startTime >= endTime) {
    ElMessage.error('录制开始时间必须早于结束时间')
    return
  }

  // 检查预估文件大小
  const estimatedBytes = recordingForm.duration * 60 * 15 * 50 * 1024 // 估算字节数
  const maxFileSize = 500 * 1024 * 1024 // 500MB限制

  if (estimatedBytes > maxFileSize) {
    try {
      await ElMessageBox.confirm(
        `预估文件大小为 ${estimatedFileSize.value}，可能会很大。是否继续？`,
        '文件大小警告',
        {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return // 用户取消
    }
  }

  recordingSaving.value = true

  try {
    // 获取客户端信息
    const client = clientsStore.getClientById(currentRecordingClientId.value)
    if (!client) {
      throw new Error('客户端信息不存在')
    }

    // 构建录屏请求
    const recordingData = {
      clientId: currentRecordingClientId.value,
      startTime: recordingForm.startTime,
      endTime: recordingForm.endTime,
      duration: recordingForm.duration
    }



    // 调用录屏生成API
    const response = await filesAPI.generateRecording(recordingData)

    if (response && response.success) {
      ElMessage.success('录屏生成请求已提交，请稍后在录屏记录管理中查看')
      recordingDialogVisible.value = false

      // 清空表单
      recordingForm.startTime = null
      recordingForm.endTime = null
      recordingForm.duration = 5
      currentRecordingClientId.value = null
    } else {
      throw new Error(response?.message || '录屏生成失败')
    }

  } catch (error) {
    console.error('录屏生成失败:', error)
    ElMessage.error(`录屏生成失败: ${error.message}`)
  } finally {
    recordingSaving.value = false
  }
}

// 手动截图
const takeClientScreenshot = async (clientId) => {
  try {
    // 获取客户端信息
    const client = clientsStore.getClientById(clientId)
    if (!client) {
      ElMessage.error('客户端信息不存在')
      return
    }

    // 构建客户端API URL
    let apiUrl
    if (client.ip && client.websocket_port) {
      // 使用客户端的IP和端口
      apiUrl = `http://${client.ip}:${client.websocket_port}/api/v1/client/screen/screenshot`
    } else {
      // 使用默认地址（本地测试）
      apiUrl = `http://127.0.0.1:8090/api/v1/client/screen/screenshot`
    }

    // 发送POST请求触发截图
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        quality: 80,
        format: 'png'
      })
    })

    const result = await response.json()

    if (result.success) {
      ElMessage.success('截图请求已发送，请稍后查看截图记录')
    } else {
      throw new Error(result.message || '截图请求失败')
    }

  } catch (error) {
    console.error('发送截图命令失败:', error)
    ElMessage.error(`截图请求失败: ${error.message}`)
  }
}

const refreshScreens = () => {
  onlineClients.value.forEach(client => {
    refreshClientScreenSharing(client.id)
  })
  ElMessage.success('已刷新所有屏幕')
}

// 导航到录屏记录管理
const goToRecordingManagement = () => {
  router.push('/behavior/recording')
}

// 导航到截屏记录管理
const goToScreenshotManagement = () => {
  router.push('/behavior/screenshot')
}

// 停止所有屏幕共享
const stopAllScreenSharing = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要停止所有客户端的屏幕共享吗？',
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    onlineClients.value.forEach(client => {
      if (clientsStore.isScreenSharingActive(client.id)) {
        stopClientScreenSharing(client.id)
      }
    })

    ElMessage.success('已停止所有屏幕共享')
  } catch {
    // 用户取消操作
  }
}

// 页面离开时的清理函数
const cleanupAllScreenSharing = async () => {
  console.log('[ScreenSharing] Cleaning up all screen sharing connections...')

  // 创建一个停止所有连接的Promise数组
  const stopPromises = []

  directConnections.forEach((connection, clientId) => {
    console.log(`[ScreenSharing] Stopping screen sharing for client ${clientId}`)

    try {
      // 1. 关闭WebSocket连接
      if (connection.ws) {
        connection.ws.close()
      }

      // 2. 清理心跳定时器
      if (connection.heartbeatInterval) {
        clearInterval(connection.heartbeatInterval)
      }

      // 3. 调用客户端API停止屏幕共享
      const client = clientsStore.getClientById(clientId)
      if (client) {
        let clientApiUrl
        if (client.ip && client.websocket_port) {
          clientApiUrl = `http://${client.ip}:${client.websocket_port}/api/v1/client/screen/stop`
        } else {
          clientApiUrl = `http://127.0.0.1:8090/api/v1/client/screen/stop`
        }

        // 发送停止请求
        const stopPromise = fetch(clientApiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
        }).catch((error) => {
          console.error(`Failed to stop screen sharing for client ${clientId}:`, error)
        })

        stopPromises.push(stopPromise)
      }

      // 4. 更新状态
      clientsStore.stopScreenSharing(clientId)
    } catch (error) {
      console.error('Error cleaning up client:', clientId, error)
    }
  })

  // 等待所有停止请求完成
  await Promise.all(stopPromises)

  // 清空连接映射
  directConnections.clear()

  console.log('[ScreenSharing] All screen sharing connections cleaned up')
}

// 浏览器关闭时的清理函数（使用sendBeacon确保能发送）
const handleBeforeUnload = () => {
  directConnections.forEach((connection, clientId) => {
    try {
      if (connection.ws) {
        connection.ws.close()
      }
      if (connection.heartbeatInterval) {
        clearInterval(connection.heartbeatInterval)
      }

      const client = clientsStore.getClientById(clientId)
      if (client) {
        let clientApiUrl
        if (client.ip && client.websocket_port) {
          clientApiUrl = `http://${client.ip}:${client.websocket_port}/api/v1/client/screen/stop`
        } else {
          clientApiUrl = `http://127.0.0.1:8090/api/v1/client/screen/stop`
        }

        // 使用 sendBeacon 确保请求能够发送
        if (navigator.sendBeacon) {
          navigator.sendBeacon(clientApiUrl, JSON.stringify({}))
        } else {
          fetch(clientApiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            keepalive: true
          }).catch(() => {})
        }
      }
    } catch (error) {
      console.error('Error cleaning up client:', clientId, error)
    }
  })
}

// 定时器变量
let hideControlsTimer
let uptimeTimer
let progressTimer

// 自动隐藏控制面板
const resetHideControlsTimer = () => {
  clearTimeout(hideControlsTimer)
  controlsHidden.value = false

  hideControlsTimer = setTimeout(() => {
    if (isFullscreen.value) {
      controlsHidden.value = true
    }
  }, 3000)
}

// 路由离开守卫 - 确保在切换路由时停止屏幕共享
onBeforeRouteLeave(async (to, from, next) => {
  console.log('[ScreenSharing] Route leaving, cleaning up screen sharing...')

  // 如果有活动的屏幕共享连接，停止它们
  if (directConnections.size > 0) {
    await cleanupAllScreenSharing()
    ElMessage.info('已自动停止所有屏幕共享')
  }

  next()
})

// 生命周期
onMounted(async () => {
  // 加载客户端数据
  await clientsStore.loadClients()

  // 检查是否需要自动启动屏幕共享
  const autoStartClientId = route.query.autoStart
  const autoFullscreen = route.query.autoFullscreen !== 'false' // 默认为true，除非明确设置为false

  if (autoStartClientId) {

    // 转换客户端ID类型 - URL参数是字符串，但API返回的ID可能是数字
    const clientId = isNaN(autoStartClientId) ? autoStartClientId : parseInt(autoStartClientId)

    // 改进的自动启动逻辑：等待客户端数据加载并重试
    const attemptAutoStart = async (retryCount = 0) => {
      const maxRetries = 5
      const retryDelay = 1000 // 1秒

      try {

        // 检查客户端是否存在 - 尝试两种ID类型
        let client = clientsStore.getClientById(clientId)
        if (!client && typeof clientId === 'number') {
          // 如果数字ID找不到，尝试字符串ID
          client = clientsStore.getClientById(clientId.toString())
        }
        if (!client && typeof clientId === 'string') {
          // 如果字符串ID找不到，尝试数字ID
          const numericId = parseInt(clientId)
          if (!isNaN(numericId)) {
            client = clientsStore.getClientById(numericId)
          }
        }

        if (!client) {
          if (retryCount < maxRetries) {
            setTimeout(() => attemptAutoStart(retryCount + 1), retryDelay)
            return
          } else {
            throw new Error(`客户端 ${clientId} 不存在或未加载`)
          }
        }

        // 检查客户端是否在线
        if (client.status !== 'online') {
          throw new Error(`客户端 ${clientId} 不在线 (状态: ${client.status})`)
        }

        // 检查客户端连接信息
        if (!client.websocket_url && (!client.ip || !client.websocket_port)) {
          throw new Error(`客户端 ${clientId} 缺少WebSocket连接信息`)
        }


        await startClientScreenSharing(clientId)
        ElMessage.success(`已自动启动客户端 ${client.name || clientId} 的屏幕共享`)

        // 如果启用了自动全屏，则在屏幕共享启动后自动进入全屏
        if (autoFullscreen) {
          setTimeout(async () => {
            try {
              await viewClientFullScreen(clientId)
              ElMessage.success(`已自动进入全屏模式`)
            } catch (error) {
              console.error('Auto-fullscreen failed:', error)
              ElMessage.warning(`自动全屏失败: ${error.message}`)
            }
          }, 2000) // 等待2秒确保屏幕共享已经建立
        }

      } catch (error) {
        console.error('Auto-start screen sharing failed:', error)
        ElMessage.error(`自动启动屏幕共享失败: ${error.message}`)
      }
    }

    // 延迟启动以确保客户端数据已加载
    setTimeout(() => attemptAutoStart(), 1500)
  }

  // 监听全屏变化
  document.addEventListener('fullscreenchange', () => {
    if (!document.fullscreenElement && isFullscreen.value) {
      // 用户按ESC退出全屏
      exitFullscreen()
    }
  })

  // 监听鼠标移动（用于显示控制面板）
  document.addEventListener('mousemove', resetHideControlsTimer)

  // 启动连接时间计时器
  uptimeTimer = setInterval(() => {
    if (fullscreenConnectionStatus.value === 'connected') {
      connectionUptime.value++
    }
  }, 1000)

  // 模拟连接进度
  progressTimer = setInterval(() => {
    if (fullscreenConnectionStatus.value === 'connecting' && connectionProgress.value < 100) {
      connectionProgress.value += 10
    } else {
      clearInterval(progressTimer)
    }
  }, 200)

  // 监听页面离开事件
  window.addEventListener('beforeunload', handleBeforeUnload)
  window.addEventListener('unload', handleBeforeUnload)
})

// 组件卸载时的清理
onUnmounted(() => {
  console.log('[ScreenSharing] Component unmounting, cleaning up...')

  // 清理定时器
  if (uptimeTimer) clearInterval(uptimeTimer)
  if (progressTimer) clearInterval(progressTimer)
  if (hideControlsTimer) clearTimeout(hideControlsTimer)

  // 移除事件监听器
  document.removeEventListener('mousemove', resetHideControlsTimer)
  window.removeEventListener('beforeunload', handleBeforeUnload)
  window.removeEventListener('unload', handleBeforeUnload)

  // 清理所有WebSocket连接 - 使用同步方式
  handleBeforeUnload()
  directConnections.clear()
})
</script>

<style scoped>
.screen-sharing-page {
  max-width: 1400px;
  margin: 0 auto;
}

/* 全屏模式样式 */
.screen-sharing-page.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  max-width: none;
  margin: 0;
  z-index: 9999;
  background: #000;
}

.fullscreen-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #000;
}

.screen-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  overflow: hidden;
}

.screen-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.screen-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-align: center;
}

.placeholder-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.6;
}

.placeholder-text {
  font-size: 18px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.control-panel {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px 24px;
  transition: all 0.3s ease;
  z-index: 1000;
}

.control-panel.hidden {
  opacity: 0;
  transform: translateX(-50%) translateY(100%);
  pointer-events: none;
}

.panel-content {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.panel-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #fff;
}

.client-info {
  font-weight: 600;
  font-size: 14px;
}

.connection-status {
  font-size: 12px;
  opacity: 0.8;
}

.connection-status.connected {
  color: #67C23A;
}

.connection-status.connecting {
  color: #E6A23C;
}

.connection-status.disconnected {
  color: #F56C6C;
}

.panel-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.stats-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  color: #fff;
  min-width: 200px;
  z-index: 1000;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.stats-title {
  font-weight: 600;
  font-size: 14px;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.stat-label {
  opacity: 0.8;
}

.stat-value {
  font-family: 'Courier New', monospace;
  font-weight: 600;
}

.stat-value.fps {
  color: #409EFF;
}

.stat-value.latency-low {
  color: #67C23A;
}

.stat-value.latency-medium {
  color: #E6A23C;
}

.stat-value.latency-high {
  color: #F56C6C;
}

/* 正常模式样式 */
.normal-mode {
  width: 100%;
}

.top-actions-card {
  margin-bottom: 20px;
}

.top-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.action-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.screen-grid {
  min-height: 200px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }

  /* 全屏模式响应式 */
  .control-panel {
    bottom: 10px;
    left: 10px;
    right: 10px;
    transform: none;
    padding: 12px 16px;
  }

  .control-panel.hidden {
    transform: translateY(100%);
  }

  .panel-content {
    flex-direction: column;
    gap: 12px;
  }

  .panel-actions {
    width: 100%;
    justify-content: center;
  }

  .stats-panel {
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
  }
}

/* 录屏对话框样式 */
.time-range-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .time-range-container {
    flex-direction: column;
    align-items: stretch;
  }

  .time-range-container span {
    text-align: center;
    margin: 5px 0;
  }
}
</style>
